package com.example.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.common.to.es.SkuEsModel;
import com.example.search.config.ElasticSearchConfig;
import com.example.search.constant.ProductConstant;
import com.example.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 创建请求对象
        IndexRequest indexRequest = new IndexRequest(ProductConstant.PRODUCT_INDEX);
        // 创建批量请求对象
        BulkRequest bulkRequest = new BulkRequest();
        // 设置请求体
        for (SkuEsModel skuEsModel : skuEsModels) {
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel),XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 发起请求
        BulkResponse bulkResp = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        return bulkResp.hasFailures();
    }
}
